$(function(){
	
	/*sideBar*/
	$('.page-sidebar').on('click', 'ul > li', function () {
		
		var fobj=$(this);
		if(fobj.hasClass('active')){
			fobj.find('ul').eq(0).slideUp(200,function(){
				fobj.removeClass('active');
			});			
		}else{
			fobj.find('ul').eq(0).slideDown(200,function(){
				fobj.addClass('active');
			});
			
			fobj.siblings('li').removeClass('active').find('ul').slideUp(200);
		}
	});
	
	$('.page-sidebar').on('click', 'li li a', function (e) {
		var current = $(this);
		var item = current.parents('li');
		current.addClass('active');
		item.siblings().find('a').removeClass('active');

		// 防止和上级点击事件冲突
		e.stopPropagation();
	});
	
});

/**
 * 
 * @param uri 
 * @param method
 * @param pageSize 每页记录数
 * @param curPage 页面大小
 * @returns
 */
function menuUrl(uri, method, pageSize, curPage){
	
	$("#page-content-wrapper").html("");
	if(pageSize == undefined){
		pageSize = 10;
	}
	
	if(curPage == undefined){
		curPage = 1;
	}
    if (/\?/.test(uri)) {
    	    uri += '&';
	    } else {
	    	uri += '?';
	    }
	uri = uri + "pv=" + method + "&pageSize=" + pageSize + "&curPage=" + curPage;
	
	$("#page-content-wrapper").load(uri);
	
}

function menuFullUrl(url){
	
	$("#page-content-wrapper").html("");
	// if(url.indexOf("?") == -1 && url.indexOf("login") == -1){
	// 	url += "?sid=" + sid;
	// } else {
	// 	url += "&sid=" + sid;
	// }

	$("#page-content-wrapper").load(url);
	
}

/**
 * 
 * @param uri 
 * @param method
 * @param pageSize 每页记录数
 * @param curPage 页面大小
 * @returns
 */
function loadData(uri, method, pageSize, curPage){
	
	$("#page-content-wrapper").html("");
	if(pageSize == undefined){
		pageSize = 10;
	}
	
	if(curPage == undefined){
		curPage = 1;
	}
	
	uri = uri + "?pv=" + method + "&pageSize=" + pageSize + "&curPage=" + curPage;
	$("#page-content-wrapper").load(uri);
	
}

function randomString(len) {
　　len = len || 32;
　　var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
　　var maxPos = $chars.length;
　　var ran = '';
　　for (i = 0; i < len; i++) {
　　　　ran += $chars.charAt(Math.floor(Math.random() * maxPos));
　　}
　　return ran;
}

function checkSid(func){
	//check/sid	
	$.ajax({
		type : "get", // 提交方式
		url : "check/sid?sid=" + sid,// 路径
		async: false,
		data : '',// 数据，这里使用的是Json格式进行传输
		dataType:"json",
		success : function(result) {// 返回数据根据结果进行相应的处理
			if (result.code == "SUCCESS") {
				if(undefined != func){
					func();
				}				
			} else {
				if(result.code == 'SID_CHECK_FAIL'){
					location.href = result.data;
					return;
				}
			}
		}
	});
	
}

/**
 * 
 * @param uri
 * @param method
 * @param id
 * @returns 修改页面
 */
function updateShow(uri, method, id){
	
	$("#page-content-wrapper").html("");
	
	uri = uri + "?pv=" + method + "&id=" + id + "&isModify=1";
	$("#page-content-wrapper").load(uri);
}



/**
 * 详情页面
 * @param uri
 * @param method
 * @param id
 * @returns
 */
function detailShow(uri, method, id){
	
	$("#page-content-wrapper").html("");
	
	uri = uri + "?pv=" + method + "&id=" + id + "&sid=" + sid;
	$("#page-content-wrapper").load(uri);
}



(function($){  
    $.fn.serializeJson=function(){  
        var serializeObj={};  
        $(this.serializeArray()).each(function(){  
            serializeObj[this.name]=this.value;  
        });  
        return serializeObj;  
    };  
})(jQuery);

function uploadFile(formId, callback){
	   
	var postData = $("#" + formId).serializeJson();	
	
	var fileIds = new Array();
    var formHandle = document.getElementById(formId);
    var tagElements = formHandle.getElementsByTagName('input');
    for (var j = 0; j < tagElements.length; j++) {
        element = tagElements[j];
        if ("file" == element.type) {
            fileIds.push(element.id);
        }
    }
	
	$.ajaxFileUpload({
	    url:"file/upload",
	    type:"POST",
	    secureuri:false,
	    fileElementId: fileIds,
	    data:postData,
	    dataType:"JSON",
	    cache:false,
	    error:function(data){
	        layer.open({
	            title:'提示信息',
	            content:'表单数据不合法!'
	        });
	    },
	    success:function(res){
	    	callback(res);
	    }
	});
   
}

function checkAll(id){
    
	var isChecked = $("input[name='all']:checked").prop("checked");
	if(isChecked){
		$('input[name="' + id + '"]').prop("checked", isChecked);
	} else {
		$('input[name="' + id + '"]').prop("checked", false);
	}

 }


function checkAllMenu(id){
    
	var isChecked = $("input[name='rootMenuList']:checked").prop("checked");
	if(isChecked){
		$('input[name="' + id + '"]').prop("checked", isChecked);
	} else {
		$('input[name="' + id + '"]').prop("checked", false);
	}

 }


function getCheckList(id){
	
    var idList = "";//定义一个数组    
    $('input[name="' + id + '"]:checked').each(function(){//遍历每一个名字为interest的复选框，其中选中的执行函数    
    	idList += $(this).val() + ",";//将选中的值添加到数组chk_value中    
    });

    return idList;
}


$(function(){
	$("#updateForm").each(function() {
        var $form = $(this);
        $form.bootstrapValidator();

        // 修复bootstrap validator重复向服务端提交bug
        $form.on('success.form.bv', function(e) {
            // Prevent form submission
            e.preventDefault();
        });


    });

});

function validReg(formId){
	$("#" + formId).each(function() {
        var $form = $(this);
        $form.bootstrapValidator();

        // 修复bootstrap validator重复向服务端提交bug
        $form.on('success.form.bv', function(e) {
            // Prevent form submission
            e.preventDefault();
        });
    });
}

function validateCallback(form, callback, confirmMsg,type) {

    var $form = $(form).closest('form');

    var data = $form.data('bootstrapValidator');
    if (data) {
    // 修复记忆的组件不验证
        data.validate();

        if (!data.isValid()) {
            return false;
        }
    }
    callback(type);

    return false;

}

function getUrlParams() {
    var paramsString = location.search;
    var reg = /([^?=&]+)=([^?=&]+)/g;
    var params = {};
    paramsString.replace(reg, function (a, b, c) {
        params[b] = c;
    });
    return params;
}




function getSid () {
    var params = getUrlParams();
    return params.sid;
}

//handle before ajax send
$(document).ajaxSend(function (ev, xhr, options) {
    var sid = getSid();
    var url = options.url;
    if (/\?/.test(url)) {
        url += '&';
    } else {
        url += '?';
    }
    url += 'sid=' + sid + "&r=" + randomString(6);
    options.url = url;
});

$(document).ajaxSuccess(function(data){
	console.log(data);
});

//禁用右键
document.oncontextmenu = function () {
  return false;
};

// 禁止点击左侧菜单和顶部菜单
var forbidLeftAndTop = {
    /**
	 *@description 禁止点击左侧菜单和顶部菜单
     */
    forbid: function () {
        var t = this;
        var tmpl = '<div style="position: absolute; top: 0; left: 0; z-index: 100000; background: url(resources/skins/bg/bg_topheader.jpg) -100px -100px no-repeat;"></div>';
        t.mask1 = $(tmpl);
        t.mask2 = $(tmpl);
        // get height of sidebar and topbar
        var topHeight = $('.navbar').outerHeight();
        var sideWidth = $('.left-sidebar').outerWidth();
        t.mask1.css({
            height: topHeight,
            width: '100%'
        });
        t.mask2.css({
            height: '100%',
            width: sideWidth
        });
        $(document.body).append(t.mask1).append(t.mask2);
    },
    /**
	 *@description 取消遮罩
     */
    cancel: function () {
        var t = this;
        t.mask1.remove();
        t.mask2.remove();
    }
};

// 防止console报错
if (typeof console === 'undefined') {
    window.console = {};
    console.log = $.noop;
    console.error = $.noop;
}

if (typeof layer !== 'undefined') {
    window.alert = function(msg){
       layer.msg(msg, {time: 1000 });
   };
}

// 兼容打印iframe
window.commonPrint = function (id) {
    if (window.frames[id] === null) {
        document.getElementById(id).focus();
        document.getElementById(id).contentWindow.print();
        //document.getElementById(id).contentDocument.execCommand('print')
    } else {
        window.frames[id].focus();
        var win = window.frames[id].contentWindow || window.frames[id];
        win.print();
    }
};